package com.hanxiaozhang.no3algorithm;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxinghua
 * @create 2023/6/14
 * @since 1.0.0
 */
public class No11TwoArraySort {

    public static void main(String[] args) {

        String[] names = new String[]{"张三", "李四", "王五"};
        String[] scores = new String[]{"89,100,61", "20,70,70", "99,100,99"};
        System.out.println(Arrays.toString(twoArraySortV1(names, scores)));
        System.out.println(Arrays.toString(twoArraySortV2(names, scores)));

    }

    /**
     * 一开始想的笨办法
     *
     * @param names
     * @param scores
     * @return
     */
    private static String[] twoArraySortV1(String[] names, String[] scores) {
        int len = names.length;
        String[] results = new String[len];
        Integer[] sums = new Integer[len];
        int sum = 0;
        for (int i = 0; i < len; i++) {
            String[] arrays = scores[i].split(",");
            for (int j = 0; j < arrays.length; j++) {
                sum += Integer.parseInt(arrays[i]);
            }
            sum = sum * 10 + i;
            sums[i] = sum;
            sum = 0;
        }
        // 排序
        Arrays.sort(sums, Comparator.reverseOrder());
        for (int i = 0; i < len; i++) {
            results[i] = names[sums[i] % 10];
        }
        return results;
    }


    /**
     * 简单写法
     *
     * @param names
     * @param scores
     * @return
     */
    private static Object[] twoArraySortV2(String[] names, String[] scores) {
        int len = names.length;
        Map<Integer, String> treeMap = new TreeMap(Comparator.reverseOrder());
        for (int i = 0; i < len; i++) {
            String[] arrays = scores[i].split(",");
            int sum = Arrays.stream(arrays).collect(Collectors.summingInt(Integer::parseInt));
            treeMap.put(sum, names[i]);
        }
        return treeMap.values().toArray();
    }


}
